import { _decorator, Component, Label, RichText } from "cc";
import { Engine } from "../Engine";
import { i18n, LanguageEvent } from "../manager/LanguageManager";
const { ccclass, property } = _decorator;

type TextComponent = RichText | Label | null;
@ccclass("LocalizedLabel")
export class LocalizedLabel extends Component {
    @property({ displayName: "key" })
    key: string = "";

    label: TextComponent = null;

    onLoad() {
        Engine.eventManager.on(LanguageEvent.CHANGE, this.updateLabel, this);

        let label: TextComponent = this.getComponent(Label);
        if (!label) {
            label = this.getComponent(RichText) as RichText;
        }
        this.label = label;
        this.updateLabel();
    }

    onDestroy() {
        Engine.eventManager.off(LanguageEvent.CHANGE, this);
    }

    /**
     * 动态修改key
     * @param args
     */
    initKey(...args: any[]) {
        this.key = Mustache.render(this.key, args);
        this.updateLabel();
    }

    /**
     * 格式化字串
     * @param obj
     */
    setString(obj: object) {
        this.label && (this.label.string = Mustache.render(this.label!.string, obj));
    }

    updateLabel() {
        this.label && (this.label.string = i18n.t(this.key));
    }
}
